<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 16:16
 */

namespace app\api\controller\v6;

use app\api\controller\v2\Auth;
use app\common\lib\exception\ApiException;
use app\common\model\FateCity;
use app\common\model\Goods;
use app\common\model\Map as MapRecode;
use app\common\model\Recode;
use think\exception\DbException;

/**
 * @title ACG地图相关接口
 * @desc 查看文章详情<br/>按页码获取文章列表，每页十条<br/>
 * @url /api/v2/article
 * @version 2.0.0
 * Class Article
 * @package app\api\controller\v2
 */
class Map extends Auth
{
    /**
     * ACG首页
     * @return \think\response\Json|bool
     * @throws ApiException
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作');
        }

        $rid = input('get.rid/d');

        if (!$rid)
        {
            return show(config('code.error'), '档案不存在');
        }

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '档案不存在');
        }
        // 获取用户当前已解锁的命格线 string 12位
        $unlockInfo = (new MapRecode())->getRecodeUnlockLines($recode, true);
        $lines = $unlockInfo['lines'];
        $planets = $unlockInfo['planets'];
        $i = 0;
        foreach ($planets['planet1'] as $k => $d)
        {
            if ($i >= 11)
            {
                continue;
            }// 仅过滤需要绘制的11颗星的数据中，未解锁购买的

            if ($lines['data'][$i] == 0)
            {
                unset($planets['planet1'][$k], $planets['planet2'][$k]);
            }
            $i++;
        }
        if ($this->is_apple_pay)
        {
            $acg_goods = $this->apple_goods['acg_goods'];
        } else
        {
            $acg_goods = (new Goods())->getGoodsForACG();
        }

        // 从配置文件中加载相关配置
        $config = config('map');

        $line_list = [];// 所有命格线商品

        foreach ($acg_goods as $ag)
        {

            if ($ag['id'] > 18)
            {
                continue;
            }// 只需要11条线的数据

            $discount = (float)$ag['discount'];// 折扣

            $price = $discount ? $ag['or_prize'] * $discount : $ag['now_prize'];// 计算实际价格

            //商品折扣活动
            $activeDiscount = active($ag['id']);
            if ($activeDiscount['discount'])
            {
                $price *= $activeDiscount['discount'];
            }

            $is_unlock = $lines['data'][$ag['id'] - 7] == 1;

            $line_list[] = [
                'gid' => $ag['id'],
                'name' => $ag['name'],
                'price' => sprintf('%.2f', $price),
                'icon' => $config['lines_icon'][$ag['id']],
                'description' => $config['lines_title'][$ag['id']],
                'color' => $config['lines_color'][$ag['id']],
                'is_unlock' => $is_unlock,
                'pid' => $config['pid'][$ag['id']],
                'planet' => $config['planet'][$ag['id']],
                'point_title' => $config['point_title'][$ag['id']],
                'point_des' => $config['point_des'][$ag['id']],
            ];
        }
        $line_list = resort($line_list, 'is_unlock');// 布尔值进行排序，暂未发现问题????

        $advertising = [
            'is_open' => true,
            'content' => config('map.advertising')['content'],
        ];

        $fate_city = [];
        //无需更新
        $update_logic = [
            'title' => '',
            'content' => '',
            'status' => 0
        ];
        // 计算命运之城数据
        if ($lines['data'][11] == 1)
        {
            $info = [
                'uid' => (int)$this->user['id'],
                'rid' => $rid,// 档案id
                'sex' => $recode['type'],// 档案性别
                'isself' => $recode['isself'],
                'longitude' => ($recode['long_deg'] + $recode['long_min'] / 60) * $recode['ew'],// 用户出生地经度
                'latitude' => ($recode['lat_deg'] + $recode['lat_min'] / 60) * $recode['ns'],// 用户出生地纬度
                'time' => strtotime($recode['year'] . '-' . $recode['month'] . '-' . $recode['day'] . ' ' . $recode['hour'] . ':' . $recode['minute'])
                    - ($recode['timezone'] + $recode['is_summer']) * 3600,// 用户出生时间
            ];
            //0=>最新逻辑，无需更新，1=》逻辑需要更新，2=》逻辑计算中
            if ($lines['status'] != 2)
            {
                $fate_city = (new FateCity())->getUserFateCitys($info);
            }

//            //获取当前最新版本逻辑信息
//            $SystemLogicModel = new SystemLogicVersion();
//            $logic_data = $SystemLogicModel->getVersion(['type' => 1]);
//            //获取当前档案逻辑版本号
//            $AppLogicModel = new AppLogicVersion();
//            $user_logic = $AppLogicModel->getVersion(['rid' => $rid, 'type' => 1]);
//
//            //更新中
//            if (Cache::get($this->user['id'].':'.$rid.'_acg_logic_status'))
//            {
//                $update_logic = [
//                    'title' => '',
//                    'content' => '',
//                    'status' => 2,
//                ];
//            } //待更新
//            elseif ($logic_data['version'] && $user_logic < $logic_data['version'])
//            {
//                $update_logic = [
//                    'title' => $logic_data['title'],
//                    'content' => $logic_data['content'],
//                    'status' => 1,
//                ];
//            }

//            $advertising['is_open'] = false;// 判断商品全部解锁后就关闭喇叭
        }

        if ($advertising['is_open'] === true && ($lines['data'] == '111111111111' || !config('map.advertising')['is_open']))
        {
            $advertising['is_open'] = false;
        }// 后台控制喇叭关闭

        $result = [
            'lines_list' => $line_list,
            'planet1' => $planets['planet1'],
            'planet2' => $planets['planet2'],
            'fate_city' => $fate_city,
            'advertising' => (object)$advertising,
            'help_url' => config('map.help_url'),
            'is_alert' => false, // TODO 弹窗信息未做
            'update_logic' => $update_logic,
        ];

        return show(config('code.success'), '加载成功', $result);
    }
}
